package com.wyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wyy.beans.Ticket;
import com.wyy.dao.TicketDao;
import com.wyy.service.TicketService;
import com.wyy.common.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class TicketServiceImpl implements TicketService {

    @Autowired
    private TicketDao ticketDao;

    @Override
    public Result<Ticket> addTicket(Ticket ticket) {
        QueryWrapper<Ticket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("license_plate_no",ticket.getLicensePlateNo());
        Ticket newTicket = ticketDao.selectOne(queryWrapper);
        if (newTicket != null) {
            return new Result<>(Result.ResultStatus.Failed.code, "不允许重复停车");
        }

        int aff = ticketDao.insert(ticket);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public Result<Ticket> getTicket(String licensePlateNo) {
        QueryWrapper<Ticket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("license_plate_no",licensePlateNo);
        Ticket newTicket = ticketDao.selectOne(queryWrapper);
        return newTicket == null ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success", newTicket);
    }

    @Override
    public Result<Ticket> deleteTicket(String licensePlateNo) {
        QueryWrapper<Ticket> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(true, "license_plate_no", licensePlateNo);
        int aff = ticketDao.delete(queryWrapper);
        return aff == 0 ? new Result<>(Result.ResultStatus.Failed.code, "fail")
                : new Result<>(Result.ResultStatus.SUCCESS.code, "success");
    }

    @Override
    public int getParkingCosts(Ticket ticket) {
        Date parkTime = ticket.getParkTime();
        Date parkUpTime = new Date();
        return getDifferHour(parkTime, parkUpTime);
    }

    private int getDifferHour(Date parkTime, Date parkUpTime) {
        long hourM = 1000 * 60 * 60;
        long differM = parkUpTime.getTime() - parkTime.getTime();
        //TO DO  不足一小时按一小时计算
        double hourD = (double) differM / hourM;
        double hour = Math.ceil(hourD);
        return Double.valueOf(hour).intValue();
    }
}
